package top.kiterunner.learning.concurrency_test.ContainerDemo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * AdorynZhao in Tencent-UESTC.
 * Source Code Created on 2017/7/6.
 */
public class WatchContainerDemo2 {

    private volatile List<Item> itemList = new ArrayList<>();

    private Object lock = new Object();

    public void add(Item item) {
        this.itemList.add(item);
    }

    public int size() {
        return this.itemList.size();
    }

    // wait会释放锁，notify不会释放锁
    public void produce() {
        System.out.println("Produce Thread Started.");
        synchronized (lock) {
            for (int i = 0; i < 10; i++) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                this.add(new Item());
                System.out.println("Adding " + i + " Item...");

                if (this.size() == 5) {
                    this.lock.notify();

                    // 思考为什么会再wait??
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public void watch() {
        System.out.println("Watch Thread Started.");
        synchronized (lock) {
            if (this.size() != 5) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println(Thread.currentThread().getName() + " Watch Over.");
            lock.notify();

            // 睡眠一秒保证能够notify线程produce的wait过程
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        WatchContainerDemo2 wcd2 = new WatchContainerDemo2();

        Thread thread1 = new Thread(wcd2::produce, "Produce_Thread");
        Thread thread2 = new Thread(wcd2::watch, "Watch_Thread");

        try {
            thread1.start();
            thread2.start();
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public class Item {
        Item() {}
    }
}
